using _ReplaceString_.UI;
using _ReplaceString_.UI.Styles;
using RSCore;
using Terraria.ModLoader.Config.UI;
using Terraria.ModLoader.UI;

namespace _ReplaceString_.UI.Elements;

public class MainElement : ConfigElement
{
	public MainElement()
	{
		DrawLabel = false;
		Width = new(0, 1);
		Append(new RealMainElement());
	}
}

internal class RealMainElement : UIBase
{
	private ModElementGroup _container;

	private UIFocusInputTextField.EventHandler? _filterHook;

	public RealMainElement()
	{
		Width = new(0, 1);
		Tag |= UITag.FlexibleHeight;
		BackgroundColor = Color.Transparent;
		AddStyle(UIBackground.Rect, UIType.Panel);
		Append(_container = new ModElementGroup());
	}

	public override void OnActivate()
	{
		var current = Parent;
		while (current is not UIModConfig)
		{
			if (current == null)
			{
				return;
			}
			current = current.Parent;
		}
		var ui = (UIModConfig)current;
		ui.filterTextField.OnTextChange += _filterHook = delegate
		{
			ui.updateNeeded = false;
			RemoveChild(_container);
			_container.ApplyFilter(ui.filterTextField.CurrentString);
			Append(_container);
			_container.Activate();
		};
	}

	public override void OnDeactivate()
	{
		if (_filterHook == null)
		{
			return;
		}
		var current = Parent;
		while (current is not UIModConfig)
		{
			if (current == null)
			{
				return;
			}
			current = current.Parent;
		}
		var ui = (UIModConfig)current;
		ui.filterTextField.OnTextChange -= _filterHook;
	}
}